#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:田野
@time: 2018/12/12
"""

# 创建序列化起，继承serializers.serializer/serializers.ModelSerializer
from rest_framework import serializers

from booktest.models import BookInfo, HeroInfo


class BookInfoSerializer(serializers.ModelSerializer):
    '''图书数据序列化器'''

    class Meta:
        model = BookInfo
        fields = '__all__'

    # def validate(self, attrs):
    #     btitle = attrs['btitle']
    #     if btitle == '语文':
    #         return attrs
    #     raise serializers.ValidationError('咋没有django呢')
        # def validate_btitle(self, value):
        #     if 'django' not in value.lower():
        #         raise serializers.ValidationError('咋没有django呢')
        # class Meta:
        #     model = BookInfo
        #     fields = '__all__'
        # def validate_btitle(self, value):
        #     if 'django' not in value.lower():
        #         raise serializers.ValidationError('图书名称必须包含DJANGO')
        #     return value
        # def validate(self, attrs):

        # def validate(self, attrs):
        #     bread = attrs['bread']
        #     bcomment = attrs['bcomment']
        #     if bread < bcomment:
        #         raise serializers.ValidationError('bread小')
        #     return attrs


class HeroInfoSerializer(serializers.Serializer):
    """英雄数据序列化器"""
    GENDER_CHOICES = (
        (0, 'male'),
        (1, 'female')
    )
    id = serializers.IntegerField(label='ID', read_only=True)
    hname = serializers.CharField(label='名字', max_length=20)
    hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False)
    hcomment = serializers.CharField(label='描述信息', max_length=200, required=False, allow_null=True)
    hbook = BookInfoSerializer(read_only=True)

    def validate(self, attrs):
        hname = attrs['hname']
        if hname == '刘备':
            return attrs
        raise serializers.ValidationError('只能是刘备！！！')

    def create(self, validated_data):
        '''新建'''
        print(validated_data)
        return HeroInfo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.btitle = validated_data.get('btitle', instance.btitle)
        instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
        instance.bread = validated_data.get('bread', instance.bread)
        instance.bcomment = validated_data.get('bcomment', instance.bcomment)
        instance.save()
        return instance
